from pptx.util import Inches, Pt
import util,math,sys
from pptx.dml.color import RGBColor
from PIL import Image
import pandas as pd
import numpy as np
from io import BytesIO

def create_layout_ppt(prs,batch,title):
    if len(batch)==0:
        return
    # 获取画布宽高
    slide_height = prs.slide_height
    slide_width = prs.slide_width
    batch_pd = pd.DataFrame(batch)

    #删除所有空列
    batch_pd = batch_pd.dropna(axis=1,how='all')

    #获取第一行作为标题
    row_title = batch_pd.iloc[0].reset_index(drop=True)[0]

    is_bytesio = batch_pd.map(lambda x: isinstance(x, BytesIO))
    #只保留有BytesIO的行
    batch_pd = batch_pd[is_bytesio.any(axis=1)].reset_index(drop=True)

    # 删除全是nan的行
    batch_pd = batch_pd.dropna(axis=0,how='all')
    #行列倒置
    batch_pd = batch_pd.T
    data = batch_pd.iloc[:, :6]
    data = batch_pd.to_dict(orient='records')
    max_per_row = 5
    # 图像尺寸和间距
    img_width = Inches(2)
    img_height = Inches(1.5)
    margin_x = Inches(0.5)
    margin_y = Inches(0.5)
    label_width = Inches(0.8)  # 行标签宽度
    # 解析数据
    titles = data[0]
    rows = data[1:]
    for row_idx, row_data in enumerate(rows):  # F1, F2, F3
        top = margin_y + (row_idx % 3) * (img_height + Inches(0.5))+ Inches(0.5)
        if row_idx % 3 == 0:
            slide = prs.slides.add_slide(prs.slide_layouts[6])
            util.add_text_box(slide,0,0.2,slide_width,Inches(0.25),title,18,text_line=True)
        label_box = slide.shapes.add_textbox(
                Inches(0.2),  # 靠左侧
                top + img_height / 2 - Inches(0.25),  # 垂直居中
                label_width,
                Inches(0.5)
            )
        label_tf = label_box.text_frame
        #显示F+行数
        label_tf.text = f"F{row_idx+1}"
        label_tf.paragraphs[0].font.size = Pt(18)

        for col_idx, img_stream in row_data.items():
            if col_idx > 4:
                continue
            #如果不是BytesIO，则跳过
            if not isinstance(img_stream, BytesIO):
                continue
            # 计算图像插入位置
            left = margin_x + (col_idx % max_per_row) * (img_width + Inches(0.5)) + Inches(0.2)
            # 添加图像
            slide.shapes.add_picture(img_stream, left, top, width=img_width, height=img_height)
            # 添加标题（只在第一行添加）
            title_text = titles[col_idx]
            img_text_box = slide.shapes.add_textbox(
                left,
                top - Inches(0.3),
                img_width,
                Inches(0.3)
            )
            img_text_box.text = title_text
            img_text_box_tf = img_text_box.text_frame
            img_text_box_tf.paragraphs[0].font.size = Pt(10)


